/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
  //存放符合条件的三元组
  let res = []
  //数组排序
  nums.sort((a, b) => a - b)

  for (let i = 0; i < nums.length - 2; i++) {
    //跳过重复的nums[i]
    if (i > 0 && nums[i - 1] === nums[i]) continue

    //双指针法
    let left = i + 1, right = nums.length - 1
    while (left < right) {
      //三数之和
      const sum = nums[i] + nums[left] + nums[right]

      if (sum === 0) {
        //将符合条件的三元组放入数组res
        res.push([nums[i], nums[left], nums[right]])
        //跳过重复的nums[left]和nums[right]
        while (left < right && nums[left] === nums[left + 1]) left++
        while (left < right && nums[right] === nums[right - 1]) right--
        //移动指针left和指针right
        left++
        right--
      } else if (sum < 0) {
        left++
      } else {
        right--
      }
    }
  }

  //返回结果数组
  return res
};
